package com.ebelter.btcomlib.models.bluetooth.base;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import com.ebelter.btcomlib.models.bluetooth.bean.ConnectStatus;
import com.ebelter.btcomlib.models.bluetooth.bean.ProductStyle;
import com.ebelter.btcomlib.models.bluetooth.bean.SendMessage;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IConnectStationCallback;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IDataReadWriteCallback;
import com.ebelter.btcomlib.models.bluetooth.products.dianji8.Dj8BytesMake;
import com.ebelter.btcomlib.models.bluetooth.products.scale.ScaleBytesMakeFatory;
import com.ebelter.btcomlib.utils.BytesUtils;
import com.ebelter.btcomlib.utils.TimeUtils;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.log.LogUtils;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.UUID;

public class ServiceGatt {


    private String TAG = "ServiceGatt";


    private long ServiceGatt_SendThread_interval = 300;//发送线程的时间间隔


    private static final int WHAT_SEND_HEART = 99;//发送心跳包的指令


    //一个蓝牙4.0的终端可以包含多个Service，一个Service可以包含多个Characteristic，
    // 一个Characteristic包含一个Value和多个Descriptor，一个Descriptor包含一个Value


    private static final int WHAT_GATT_RECONNECT = 1;//重连
    private static final int WHAT_CONNECTED = 2;//连接
    private static final int WHAT_DISCONNECTED = 3;//断开
    private static final int WHAT_CONNECTING = 4;//断开

    private Context context;//上下文

    private ProductStyle productStyle;//此次连接的产品类型

    private String serviceUUID;       //服务的
    private String[] deviceReadNotifyUUIDs; //读
    private String[] deviceWriteUUIDs;//写


    /**
     * 发送数据缓冲区
     */
    private Queue<SendMessage> sendMessagesBufferQueue = null;  //queue.offer()  //queue.poll()

    private SendThread mSendThread;//发送消息的线程

    private MyHandle myHandle;//Main_Handle

    private BluetoothDevice connectBluetoothDevice;//要连接的蓝牙设备


    private BluetoothGatt mBluetoothGatt;

    private BluetoothGattService mBluetoothGattService;

    private ConnectStatus connectStatus = ConnectStatus.DISCONNECTED;//设备的连接状态 有三种状态 已连接 正在连接 断开

    private IConnectStationCallback mIConnectStationCallback;//连接状态回调

    private IDataReadWriteCallback mIDataReadWriteCallback;//读写的回调


    //记录上上一条发送数据的时间
    private long lastSendMsgTime; //记录上一次发送消息的时间

    void setConnectCallback(IConnectStationCallback mIConnectStationCallback) {
        this.mIConnectStationCallback = mIConnectStationCallback;
    }

    public void setIDataReadWriteCallback(IDataReadWriteCallback mIDataReadWriteCallback) {
        this.mIDataReadWriteCallback = mIDataReadWriteCallback;
    }

    ServiceGatt(Context context, ProductStyle productStyle, String serviceUUID, String[] writeUUIDs,
                String[] readUUIDs, boolean hasSendThread, long serviceGatt_SendThread_interval) {
        this.productStyle = productStyle;
        TAG = productStyle.getProductName() + "ServiceGatt";
        this.serviceUUID = serviceUUID.substring(0, 23);
        this.deviceWriteUUIDs = writeUUIDs;
        this.deviceReadNotifyUUIDs = readUUIDs;
        this.context = context;
        this.ServiceGatt_SendThread_interval = serviceGatt_SendThread_interval;

        myHandle = new MyHandle(context);

        sendMessagesBufferQueue = new LinkedList<>();//发送缓存区


        if (hasSendThread) {//hasSendThread为true说明有下发信息的 有的产品没有下发信息只是读取的这里一般传进来false
            sendThreadRunFlag = true;
            mSendThread = new SendThread();
            mSendThread.start();
        }

    }

    public boolean addSendMsg(SendMessage message) {
        return sendMessagesBufferQueue != null && sendMessagesBufferQueue.add(message);
    }

    boolean addSendMsgs(List<SendMessage> messages) {
        return sendMessagesBufferQueue != null && sendMessagesBufferQueue.addAll(messages);
    }


    private int mBluetoothGattConnectCount;

    void connectBluetoothDevice(final BluetoothDevice connectBD) {
        if (connectBD == null) {
            return;
        }

        if (isConnect()) {//正在连接着
            if (TextUtils.equals(connectBD.getAddress(), this.connectBluetoothDevice.getAddress())) {
                //正在连接着 地址跟传进来的地址是一样的
                LogUtils.i(TAG, connectBD.getAddress() + "--A1--已经连接无需重新连接 没有任何操作");

            } else {
                //正在连接着 地址跟传进来的地址是 不一样的
                LogUtils.i(TAG, connectBD.getAddress() + "--A2--正在连接着 地址跟传进来的地址是 不一样的 执行清除缓存clearBlueGatt(true)和开始连接gattConnect()");
                clearBlueGatt(true);//断开连接的意思  然后重新连接新的蓝牙设备
                this.connectBluetoothDevice = connectBD;
                gattConnect();
            }

        } else {//没有连接着

            if (mBluetoothGatt != null && TextUtils.equals(mBluetoothGatt.getDevice().getAddress(), connectBD.getAddress())) {
                //没有连接着 并且mBluetoothGatt不为空且上一次连接着的地址跟这次是一样的
                LogUtils.i(TAG, connectBD.getAddress() + "--B1--没有连接着 并且mBluetoothGatt不为空且上一次连接着的地址跟这次是一样的");
                mBluetoothGattConnectCount++;
                if (mBluetoothGattConnectCount < 2) {
                    LogUtils.i(TAG, connectBD.getAddress() + "--B11--mBluetoothGattConnectCount少于2 准备采用的是mBluetoothGatt.connect()连接");


                    boolean isSF = getBluetoothGattConnectSuccessFlag(connectBD.getAddress());
                    LogUtils.i(TAG,"获取能能否通过BluetoothGattConnectSuccessFlag的标志 isSF = "+isSF);

                    if (isSF){
                        LogUtils.i(TAG,"--B11--1--isSF = true 最终决定的是 mBluetoothGatt.connect()连接");
                        mBluetoothGatt.connect();
                        if(myHandle!=null){
                            myHandle.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (!isConnect()){
                                        LogUtils.i(TAG,"--B11--1--1-mBluetoothGatt.connect()-----2秒后检测还是---没有连接成功-- 把标志置为了false 并且决定采用了---clearBlueGatt和gattConnect（）连接");
                                        setBluetoothGattConnectSuccessFlag(connectBD.getAddress(),false);

                                        //两秒钟还没连接成功就采用了
                                        clearBlueGatt(false);//断开连接的意思
                                        gattConnect();
                                    }else {
                                        LogUtils.i(TAG,"--B11--1--2-mBluetoothGatt.connect()-----2秒后检测---连接成功了-- 把标志置为了true");
                                        setBluetoothGattConnectSuccessFlag(connectBD.getAddress(),true);
                                    }

                                }
                            },2000);
                        }

                    }else {

                        LogUtils.i(TAG,"--B11--2--isSF = false 最终决定的是 采用的clearBlueGatt和gattConnect（）连接");
                        clearBlueGatt(false);//断开连接的意思
                        gattConnect();
                    }






                } else {
                    LogUtils.i(TAG, connectBluetoothDevice.getAddress() + "--B12--mBluetoothGattConnectCount大于等于2 采用的clearBlueGatt和gattConnect（）连接");
                    clearBlueGatt(false);//断开连接的意思
                    gattConnect();
                }
            } else {
                //没有连接着 并且mBluetoothGatt不为空且上一次连接着的地址跟这次是一样这一条件 没有成立 需重新连接
                LogUtils.i(TAG, connectBD.getAddress() + "--B2--没有连接着 地址跟传进来的地址是 不一样的 执行清除缓存clearBlueGatt(true)和开始连接gattConnect()");
                clearBlueGatt(false);//断开连接的意思
                this.connectBluetoothDevice = connectBD;
                gattConnect();

            }
        }
    }


    //获取能能否通过BluetoothGattConnectSuccessFlag的标志 默认为可以成功的
    private boolean getBluetoothGattConnectSuccessFlag(String key){
        return UserSpUtil.readBoolean(key,true);
    }
    private void setBluetoothGattConnectSuccessFlag(String key,boolean flag){
        UserSpUtil.writeBoolean(key,flag);
    }

    private void gattConnect() {
        if (connectBluetoothDevice != null) {
            mBluetoothGatt = connectBluetoothDevice.connectGatt(context, false, mGattCallback);
            if (mBluetoothGatt != null) {
                LogUtils.i(TAG, "gattConnect2Disconnect------------准备连接的是:" + mBluetoothGatt.getDevice().getName());

            }
        }

    }


    //sendfront是否要发送给前端的意思
    void clearBlueGatt(boolean sendfront) {
        LogUtils.i(TAG, "gattConnect2Disconnect------------clearBlueGatt（sendfront） sendfront = " + sendfront);
        try {
            if (mBluetoothGatt != null) {
                mBluetoothGatt.disconnect();
                mBluetoothGatt.close();
                mBluetoothGatt = null;
                mBluetoothGattService = null;
                mBluetoothGattConnectCount = 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        connectStatus = ConnectStatus.DISCONNECTED;
        if (sendfront) {
            sendEmptyMessage(WHAT_DISCONNECTED, 0);//回调给前端
        }
    }


    private void clearBlueGatt() {
        clearBlueGatt(true);
    }

    void disConnect(boolean sendfront) {
        try {
            if (mBluetoothGatt != null) {
                mBluetoothGatt.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        connectStatus = ConnectStatus.DISCONNECTED;
        if (sendfront) {
            sendEmptyMessage(WHAT_DISCONNECTED, 0);//回调给前端
        }
    }

    private void sendEmptyMessage(int what, long delay) {
        if (myHandle != null) {
            myHandle.sendEmptyMessageDelayed(what, delay);
        }
    }

    private void sendMessage(int what, Object object) {
        if (myHandle != null) {
            Message message = myHandle.obtainMessage();
            message.what = what;
            message.obj = object;
            myHandle.sendMessage(message);
        }
    }

    //连接回调信息
    private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        //----------------------------------------------1
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            LogUtils.i(TAG, "---onConnectionStateChange, status:" + status + ",new status:" + newState);//0 2 表示连接成功
            if (status == BluetoothGatt.GATT_SUCCESS) {
                if (newState == BluetoothProfile.STATE_CONNECTED) {
                    if (gatt != null) {
                        boolean success = gatt.discoverServices();

                        connectStatus = ConnectStatus.CONNECTING;
                        sendMessage(WHAT_CONNECTING, connectBluetoothDevice);
                        LogUtils.i(TAG, "---onConnectionStateChange, ----> gatt.discoverServices() success = " + success);
                    }

                } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                    LogUtils.i(TAG, "---onConnectionStateChange,newState == BluetoothProfile.STATE_DISCONNECTED");

                    if (isConnect()) {
                        connectStatus = ConnectStatus.DISCONNECTED;
                        sendEmptyMessage(WHAT_DISCONNECTED, 0);//回调给前端

                    }

                }

            } else {
                LogUtils.i(TAG, "---onConnectionStateChange,status!=BluetoothGatt.GATT_SUCCESS");
                //回调给前端接口
                if (isConnect()) {
                    connectStatus = ConnectStatus.DISCONNECTED;
                    sendEmptyMessage(WHAT_DISCONNECTED, 0);//回调给前端

                }

            }
        }


        //------------------------------------------------2
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            LogUtils.i(TAG, "---onServicesDiscovered status = " + status);

            if (status == BluetoothGatt.GATT_SUCCESS) {
                //打印出当前设备的services列表
                List<BluetoothGattService> gattServices = gatt.getServices();

                String serviceUUID2 = "";
                for (BluetoothGattService service : gattServices) {
                    String sid = service.getUuid().toString();
                    LogUtils.i(TAG, "-----onServicesDiscovered-------service uuid:" + sid);
                    if (sid.contains(serviceUUID)) {
                        serviceUUID2 = sid;
                        LogUtils.i(TAG, "-----onServicesDiscovered-------service uuid: 匹配成功 serviceUUID = " + serviceUUID2);
                    }
                }

                if (TextUtils.isEmpty(serviceUUID2)) {
                    LogUtils.i(TAG, "-----onServicesDiscovered-------service没找到: 匹配失败");
                    return;
                }
                mBluetoothGattService = null;
                mBluetoothGattService = gatt.getService(UUID.fromString(serviceUUID2));

                if (mBluetoothGattService == null) {
                    LogUtils.i(TAG, "---------service-----匹配失败");
                    //  clearBlueGatt();
                    sendEmptyMessage(WHAT_DISCONNECTED, 0);
                    sendEmptyMessage(WHAT_GATT_RECONNECT, 0);
                    connectStatus = ConnectStatus.DISCONNECTED;
                    return;
                } else {
                    LogUtils.i(TAG, "---------service-----匹配成功");

                }
                List<BluetoothGattCharacteristic> characteristics = mBluetoothGattService.getCharacteristics();

                if (productStyle != null && productStyle != ProductStyle.THREE_IN_ONE) {//经测量 血压计不全部打开 回不来数据
                    for (BluetoothGattCharacteristic characteristic : characteristics) {
                        LogUtils.i(TAG, "-----onServicesDiscovered-------characteristic uuid:" + characteristic.getUuid().toString());
                        setCharacteristicNotification(characteristic, true);
                    }
                }
                BluetoothGattCharacteristic characteristic = mBluetoothGattService.getCharacteristic(UUID.fromString(deviceReadNotifyUUIDs[0]));
                if (characteristic != null) {
                    connectStatus = ConnectStatus.CONNECTED;
                    setCharacteristicNotification(characteristic, true);
                    //  sendMessage(WHAT_CONNECTED,connectBluetoothDevice);
                } else {
                    LogUtils.i(TAG, "---------service-----characteristic = null 出现异常");
                }


            } else {
                LogUtils.i(TAG, "---onServicesDiscovered status != BluetoothGatt.GATT_SUCCESS");
                connectStatus = ConnectStatus.DISCONNECTED;
                //clearBlueGatt();
                sendEmptyMessage(WHAT_DISCONNECTED, 0);
            }

        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorWrite(gatt, descriptor, status);

            LogUtils.i(TAG, "--------------onDescriptorWrite---------------status = " + status);
            if (status != 0) {
                LogUtils.i(TAG, "onDescriptorWrite, status not 0, do disconnect.");
                // clearBlueGatt();
                connectStatus = ConnectStatus.DISCONNECTED;
                sendEmptyMessage(WHAT_DISCONNECTED, 0);
            } else {
                UUID uuid = descriptor.getCharacteristic().getUuid();
                LogUtils.i(TAG, "-----onDescriptorWrite------UUID = " + uuid + ", deviceReadNotifyUUIDs.length = " + deviceReadNotifyUUIDs.length);
                //设置多通道通知
                if (deviceReadNotifyUUIDs.length > 1) {
                    setMutiNotify(uuid, 1);
                }
                if (deviceReadNotifyUUIDs.length > 2) {
                    setMutiNotify(uuid, 2);
                }

                if (deviceReadNotifyUUIDs.length > 3) {
                    setMutiNotify(uuid, 3);
                }
                connectStatus = ConnectStatus.CONNECTED;
                sendMessage(WHAT_CONNECTED, connectBluetoothDevice);

                //查询蓝牙固件版本信息

//                    BluetoothGattService deviceInfomaction = gatt.getService(UUID.fromString("0000180a-0000-1000-8000-00805f9b34fb"));
//                    BluetoothGattCharacteristic bleFirmwareCharacteristic = deviceInfomaction.getCharacteristic(UUID.fromString("00002a26-0000-1000-8000-00805f9b34fb"));
//                    mBluetoothGatt.readCharacteristic(bleFirmwareCharacteristic);//-----------------zcq1805301741删除

            }

        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            //读取到数据
            LogUtils.i(TAG, "received--------------onCharacteristicRead---------------status = " + status + "\n" + BytesUtils.bytes2HexStr(characteristic.getValue()));

        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            LogUtils.i(TAG, "zengcaiqing-received----------onCharacteristicChanged () = " + BytesUtils.bytes2HexStr(characteristic.getValue()));
            if (isConnect() && mIDataReadWriteCallback != null) {
                mIDataReadWriteCallback.onCharacteristicChanged(characteristic.getValue());
            }

        }


    };

    private void setMutiNotify(UUID uuid, int channelNumber) {
        if (mBluetoothGattService != null) {
            if (uuid.toString().equals(deviceReadNotifyUUIDs[channelNumber - 1])) {
                LogUtils.i(TAG, "-----onDescriptorWrite---characteristic " + (channelNumber - 1) + "----set notifty characteristic " + channelNumber);
                BluetoothGattCharacteristic characteristic = mBluetoothGattService.getCharacteristic(UUID.fromString(deviceReadNotifyUUIDs[channelNumber]));
                if (characteristic != null) {
                    setCharacteristicNotification(characteristic, true);
                }
            }
        }

    }


    private final static String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";

    private void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enable) {
        if (mBluetoothGatt != null && characteristic != null) {
            mBluetoothGatt.setCharacteristicNotification(characteristic, enable);
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG));
            if (descriptor != null) {
                LogUtils.i(TAG, "mBluetoothGatt.writeDescriptor.");
                descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                mBluetoothGatt.writeDescriptor(descriptor);
            }
        } else {
            LogUtils.i(TAG, "setCharacteristicNotification-mBluetoothGatt = null 状态异常");
        }

    }


    //把数据发送出去 true说明发送成功 false说明发送失败
    private boolean writeData(byte[] data) {
        if (data == null) {
            LogUtils.e(TAG, "写入的数据不能为空");
            return false;
        }
        if (mBluetoothGatt == null) {
            LogUtils.e(TAG, "----mBluetoothGatt = null 写入失败");
            return false;
        }
        if (mBluetoothGattService == null) {
            LogUtils.e(TAG, "----mBluetoothGattService = null 写入失败");
            return false;
        }

        BluetoothGattCharacteristic alertLevel = mBluetoothGattService.getCharacteristic(UUID.fromString(deviceWriteUUIDs[0]));

        if (alertLevel == null) {
            LogUtils.e(TAG, "----alertLevel = null 写入失败");
            return false;
        }

        boolean status;
        int storedLevel = alertLevel.getWriteType();
        LogUtils.i(TAG, "storedLevel() - storedLevel=" + storedLevel);
        alertLevel.setValue(data);
        alertLevel.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
        status = mBluetoothGatt.writeCharacteristic(alertLevel);
        LogUtils.i(TAG, "writeLlsAlertLevel() - status=" + status);
        if (mIDataReadWriteCallback != null) {
            mIDataReadWriteCallback.writeData(data);
        }
        return status;

    }

    boolean isConnect() {
        return connectBluetoothDevice != null && connectStatus == ConnectStatus.CONNECTED;
    }




    @SuppressLint("HandlerLeak")
    private class MyHandle extends Handler {
        private WeakReference<Context> mWeakReference;

        MyHandle(Context context) {
            super(Looper.getMainLooper());
            mWeakReference = new WeakReference<>(context);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mWeakReference == null || mWeakReference.get() == null) {
                return;
            }
            //  LogUtils.i(TAG,"--MyHandle()--msg.what"+msg.what);
            switch (msg.what) {
                case WHAT_GATT_RECONNECT:
                    gattConnect();
                    break;
                case WHAT_CONNECTED:
                    if (mIConnectStationCallback != null) {
                        mIConnectStationCallback.onConnected(productStyle, (BluetoothDevice) msg.obj);
                    }
                    break;
                case WHAT_DISCONNECTED:
                    // clearBlueGatt(false);//清空
                    if (mIConnectStationCallback != null)
                        mIConnectStationCallback.onDisConnected(productStyle);
                    break;
                case WHAT_CONNECTING:
                    if (mIConnectStationCallback != null)
                        mIConnectStationCallback.onConnecting(productStyle, (BluetoothDevice) msg.obj);
                    break;
                case WHAT_SEND_HEART:
                    //发送一个心跳包过去
                    addHeart();
                    break;

            }

        }

        private void exitHandle() {
            removeCallbacksAndMessages(null);
            if (mWeakReference != null) {
                mWeakReference.clear();
                mWeakReference = null;
            }
        }
    }

    //添加一个心跳包的意思
    private void addHeart() {
        if (productStyle == ProductStyle.SCALE && isConnect()) {//手动添加体脂秤的心跳包
            LogUtils.i(TAG, "手动添加了一个体脂秤的心跳包");
            addSendMsg(ScaleBytesMakeFatory.getHEARTSmg());
        }else if (productStyle == ProductStyle.DJ8 && isConnect()){
            LogUtils.i(TAG, "8电极设备-手动添加了一个体脂秤的心跳包");
            addSendMsg(Dj8BytesMake.getDj8HeartSendMessage());
        }
    }


    public void exit() {
        clearBlueGatt();
        if (myHandle != null) {
            myHandle.exitHandle();
            myHandle = null;
        }
        context = null;
        connectBluetoothDevice = null;
        sendThreadRunFlag = false;
        if (mSendThread != null) {
            mSendThread.interrupt();//中断掉死循环线程
            mSendThread = null;
        }

    }

    private boolean sendThreadRunFlag = true;

    /**
     * 发送数据的线程
     */
    private class SendThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (sendThreadRunFlag) {
                // LogUtils.i(TAG,productStyle.getProductName()+"---SendThread线程----"+ TimeUtils.getCurrentTime1());
                if (connectStatus == ConnectStatus.CONNECTED) {
                    //  LogUtils.i(TAG,"---SendThread线程----蓝牙连接成功");
                    if (sendMessagesBufferQueue != null && sendMessagesBufferQueue.size() > 0) {//发送缓存池里面有数据
                        // LogUtils.i(TAG,"---SendThread线程----蓝牙连接成功-sendMessagesBufferQueue.size="+sendMessagesBufferQueue.size());
                        SendMessage sendMessage = sendMessagesBufferQueue.poll();//remove() 和 poll() 方法都是从队列中删除第一个元素
                        if (sendMessage != null && sendMessage.datas != null && sendMessage.datas.length > 0) {//判断发送的数据是不是真实存在的
                            sendMessage.sendCount++;//此消息发送的次数加1
                            boolean sendResultFlag = writeData(encrypt(sendMessage.isNeedEncrypt, sendMessage.datas));
                            if (sendResultFlag) {
                                lastSendMsgTime = System.currentTimeMillis();//记录一下发送消息成功的时间
                            }
                            if (LogUtils.isDebug) {//当log日志打开的时候输出发送的描述信息
                                StringBuilder desc = new StringBuilder();
                                desc.append(sendMessage.desc).append("---");
                                if (sendResultFlag) {
                                    desc.append("zengcaiqing-发送成功 ").append(BytesUtils.bytes2HexStr(sendMessage.datas));
                                    // sendLog2("--------------------\n"+sendMessage.desc+"  发送成功");
                                } else {
                                    desc.append("发送失败");
                                    // sendLog2(sendMessage.desc+"  发送失败");
                                }
                                LogUtils.i(TAG, "---SendThread线程----" + desc.toString());
                            }

                            if (!sendResultFlag) {//如果发送失败的意思 就需要判断一下这条消息是否要重新加入队列里面重新发送
                                int sendCount = sendMessage.sendCount;
                                int reSendCount = sendMessage.reSendCount;
                                String desc = sendMessage.desc;
                                String addDescStr = "#" + TimeUtils.getCurrentTime1() + "--发送 sendCount=" + sendCount + "次失败";
                                sendMessage.desc = desc + addDescStr;
                                if (sendCount < reSendCount + 1) {//如果发送失败并且需要重复发送的数据 需要加到队列里面重新发送
                                    if (sendMessagesBufferQueue != null)
                                        sendMessagesBufferQueue.add(sendMessage);
                                }
                            }
                        }

                    }

                    if (System.currentTimeMillis() - lastSendMsgTime >= 2000) {
                        //当前时间与上一次的发送数据成功的时间如果超过1秒钟没有数据交互就要手动添加一个心跳包
                        //这个时间自己定
                        startSendHeart();
                    }


                } else {

                    // LogUtils.i(TAG,"---SendThread线程----蓝牙连接失败");
                    if (myHandle != null) {
                        myHandle.removeMessages(WHAT_SEND_HEART);//既然已经断开连接了 就没必要发送心跳包了
                    }
                    if (sendMessagesBufferQueue != null) {
                        sendMessagesBufferQueue.clear();
                    }//连接断开了把里面的数据清空的意思
                }


                long sleeptime;
                if (sendMessagesBufferQueue != null && sendMessagesBufferQueue.size() > 0) {
                    sleeptime = 20;
                } else {
                    sleeptime = ServiceGatt_SendThread_interval;
                }
                SystemClock.sleep(sleeptime);
            }

        }
    }

    //开始发送心跳包
    private void startSendHeart() {
        if (myHandle != null) {
            myHandle.removeMessages(WHAT_SEND_HEART);
            myHandle.sendEmptyMessage(WHAT_SEND_HEART);
        }
    }

    private static final byte[] deviceAddressBytes = new byte[]{0x16, 0x15, 0x14, 0x13, 0x12, 0x11};

    private byte[] encrypt(boolean needencrypt, byte[] data) {
        if (productStyle != null && productStyle == ProductStyle.SCALE && needencrypt) {//如果是体脂秤要进行数据加密处理
            LogUtils.i(TAG, "----encript--- before --data = " + BytesUtils.bytes2HexStr(data));
            byte[] encryptData = BytesUtils.copyBytes(data);
            if ((data[0] & 0xff) == (0xab & 0xff)) {//体脂秤的数据需要加密 对比数据头
                for (int i = 3, j = 0; i < encryptData.length; i++, j++) {
                    encryptData[i] ^= deviceAddressBytes[j % 6];
                }
            }
            LogUtils.i(TAG, "----encript-----data = " + BytesUtils.bytes2HexStr(encryptData));
            return encryptData;
        }
        return data;
    }

    String getConnectBluetoothAddress() {
        if (connectBluetoothDevice != null && isConnect()) {
            return connectBluetoothDevice.getAddress();
        }
        return null;
    }


    BluetoothDevice getConnectBluetooth() {
        if (connectBluetoothDevice != null && isConnect()) {
            return connectBluetoothDevice;
        }
        return null;
    }
}
